﻿using System;
using System.Data;
using System.ComponentModel;
using System.Text;
using System.Collections.Specialized;

/// <summary>
/// Description of Model.
/// </summary>
public class Users
{
    #region BaseProperty

    public string UserId { get; set; }
    public string UserName { get; set; }
    public string UserPassword { get; set; }
    public int Status { get; set; }

    //public bool Sex { get; set; }
    //public int Age { get; set; }
    //public string Feature { get; set; }

    #endregion

    #region ExtenseFunction

    public Users UserInsert()
    {
        DB db = DB.getInstance();
        db.Excute(string.Format("insert into [User](UserId,UserName,UserPassword,CreateDate,Status)values({0},{1},{2},{3},{4})", db.DB_Safe_String(db.NewId), db.DB_Safe_String(UserName), db.DB_Safe_String(UnitSecurity.MD5(UserPassword)), db.DB_Safe_DateTime(DateTime.Now.ToString("yyyy-MM-DD HH:mm:ss")), db.DB_Parse_Number(Status)));
        return this;
    }

    public bool UserLogin()
    {
        DB db = DB.getInstance();
        foreach (DataRow i in db.List(string.Format("select * from [User] where UserName={0};", db.DB_Safe_String(UserName))).Rows)
        {
            if (i["UserPassword"] != null && i["UserPassword"].ToString() == UnitSecurity.MD5(UserPassword))
            {
                UserId = i["UserId"] == DBNull.Value ? string.Empty : i["UserId"].ToString();
                ApplictionData.CurrentUser = this;
                return true;
            }
            else
            {
                return false;
            }
        }
        return false;
    }

    public void UserLogout()
    {
        ApplictionData.CurrentUser = new Users { };
    }

    #endregion

    #region ExtenseFunction

    public DataTable List(string UserName, string Telephone, string Email, string CreateDateBegin, string CreateDateEnd)
    {
        StringBuilder sb = null;

        DB db = DB.getInstance();

        if (!string.IsNullOrEmpty(UserName))
        {
            if (sb == null)
                sb = new StringBuilder(" where");
            else
                sb.Append(" and");
            sb.Append(string.Format(" UserName={0}", db.DB_Safe_String(UserName)));
        }
        if (!string.IsNullOrEmpty(Telephone))
        {
            if (sb == null)
                sb = new StringBuilder(" where");
            else
                sb.Append(" and");
            sb.Append(string.Format(" Telephone={0}", db.DB_Safe_String(Telephone)));
        }
        if (!string.IsNullOrEmpty(Email))
        {
            if (sb == null)
                sb = new StringBuilder(" where");
            else
                sb.Append(" and");
            sb.Append(string.Format(" Email={0}", db.DB_Safe_String(Email)));
        }
        if (!string.IsNullOrEmpty(CreateDateBegin))
        {
            if (sb == null)
                sb = new StringBuilder(" where");
            else
                sb.Append(" and");
            sb.Append(string.Format(" CreateDate>{0}", db.DB_Safe_String(CreateDateBegin)));
        }
        if (!string.IsNullOrEmpty(CreateDateEnd))
        {
            if (sb == null)
                sb = new StringBuilder(" where");
            else
                sb.Append(" and");
            sb.Append(string.Format(" CreateDate<{0}", db.DB_Safe_String(CreateDateEnd)));
        }
        return db.List(string.Format("select * from [UserExtense]{0}", sb == null ? string.Empty : sb.ToString()));
    }

    #endregion
}

public class UserExtense : Users
{
    #region BaseProperty

    //public string UserId { get; set; }
    //public string UserName { get; set; }
    /// <summary>
    /// 1male,-1female
    /// </summary>
    public int Sex { get; set; }
    public string BirthDay { get; set; }
    public string Email { get; set; }
    public string Telephone { get; set; }
    public string BodyProperty { get; set; }
    public string CreateDate { get; set; }
    public new int Status { get; set; }
    public string People { get; set; }

    #endregion

    #region ExtenseProperty

    public UserExtense Insert()
    {
        DB db = DB.getInstance();
        UserId = db.NewId;
        StringBuilder sb = new StringBuilder(string.Format(@"insert into [UserExtense] ([UserId],[UserName],[BirthDay],[Email],[Telephone],[BodyProperty],[Status],[CreateDate],[UserSex],[People])values({0},{1},{2},{3},{4},{5},{6},{7},{8},{9});", db.DB_Safe_String(UserId), db.DB_Safe_String(UserName), db.DB_Safe_DateTime(BirthDay), db.DB_Safe_String(Email), db.DB_Safe_String(Telephone), db.DB_Safe_String(BodyProperty), db.DB_Safe_Number("1"), db.DB_Safe_DateTime(CreateDate), db.DB_Safe_Number(Sex), db.DB_Safe_String(People)));
        db.Excute(sb.ToString());
        return this;
    }

    public UserExtense Update()
    {
        DB db = DB.getInstance();
        StringBuilder sb = new StringBuilder(string.Format("update [UserExtense] set [UserName]={1},[BirthDay]={2},[Email]={3},[Telephone]={4},[BodyProperty]={5},[Status]={6},[CreateDate]={7},[UserSex]={8},[People]={9} where [UserId]={0};", db.DB_Safe_String(UserId), db.DB_Safe_String(UserName), db.DB_Safe_DateTime(BirthDay), db.DB_Safe_String(Email), db.DB_Safe_String(Telephone), db.DB_Safe_String(BodyProperty), db.DB_Safe_Number("1"), db.DB_Safe_DateTime(CreateDate), db.DB_Safe_Number(Sex), db.DB_Safe_String(People)));
        db.Excute(sb.ToString());
        return this;
    }

    #endregion
}

public class Diagnosis
{
    #region BaseProperty

    public string Id { get; set; }
    public string DoctorId { get; set; }
    public string PatientId { get; set; }

    public string Property_Look { get; set; }
    public string Property_Ask { get; set; }
    public string Property_Listen { get; set; }
    public string Property_Touch { get; set; }
    

    public string CreateDate { get; set; }

    public string Remarks { get; set; }

    public string Reseaon { get; set; }

    public string Massage { get; set; }

    public int Status { get; set; }

    #endregion

    #region ExtenseProperty

    public Users Doctor { get; set; }
    public UserExtense Patient { get; set; }
    public string CreateDay { get; set; }

    public string[] Drugs { get; set; }

    #endregion

    #region ExtenseFunction

    public static Diagnosis Single(string Id)
    {
        DB db = DB.getInstance();
        foreach (DataRow i in db.List(string.Format(@"select a.Status as DiagnosisStatus, a.*,b.*,c.DrugsContent from Diagnosis as a inner join UserExtense as b on a.PatientId=b.UserId inner join DiagnosisDrugs as c on a.Id=c.Id where a.Id={0}", db.DB_Safe_String(Id))).Rows)
        {
            Diagnosis dg = new Diagnosis
            {
                Id = Id,
                PatientId = db.DB_Parse_String(i["UserId"]),
                DoctorId = db.DB_Parse_String(i["DoctorId"]),
                Patient = new UserExtense
                {
                    UserId = db.DB_Parse_String(i["UserId"]),
                    UserName = db.DB_Parse_String(i["UserName"]),
                    BirthDay = db.DB_Parse_String(i["BirthDay"]),
                    BodyProperty = db.DB_Parse_String(i["BodyProperty"]),
                    Telephone = db.DB_Parse_String(i["Telephone"]),
                    Sex = db.DB_Parse_Number(i["UserSex"]),
                    Email = db.DB_Parse_String(i["Email"]),
                    People = db.DB_Parse_String(i["People"]),
                },
                Property_Ask = db.DB_Parse_String(i["P_Ask"]),
                Property_Look = db.DB_Parse_String(i["P_Look"]),
                Property_Listen = db.DB_Parse_String(i["P_Listen"]),
                Property_Touch = db.DB_Parse_String(i["P_Touch"]),
                Remarks = db.DB_Parse_String(i["Remarks"]),
                Drugs = new string[] { db.DB_Parse_String(i["DrugsContent"]) },
                Status = db.DB_Parse_Number(i["DiagnosisStatus"]),
                Reseaon = db.DB_Parse_String(i["Reseaon"]),
                Massage = db.DB_Parse_String(i["Massage"]),
                CreateDate=db.DB_Parse_String(i["CreateDate"]),
                CreateDay=db.DB_Parse_String(i["CreateDate"])
            };
            return dg;
        }
        return null;
    }

    public Diagnosis Insert()
    {
        DB db = DB.getInstance();
        IDbTransaction ta = db.Connection().BeginTransaction();

        Id = db.NewId;
        if (Drugs != null && Drugs.Length > 0)
        {
            StringBuilder sb = null;
            foreach (string i in Drugs)
            {
                if (sb == null)
                    sb = new StringBuilder();
                else
                    sb.Append(",");
                sb.Append(i);
            }
            db.Affected(string.Format("insert into DiagnosisDrugs([Id],[DrugsContent],[Status])values({0},{1},1);", db.DB_Safe_String(Id), db.DB_Safe_String(sb.ToString())));
        }
        if (Patient != null)
        {
            if (string.IsNullOrEmpty(Patient.UserId))
            {
                Patient = Patient.Insert();
            }
            else
            {
                Patient = Patient.Update();
            }
        }
        db.Affected(string.Format("insert into [Diagnosis]([Id],[DoctorId],[PatientId],[CreateDate],[P_Ask],[P_Look],[P_Listen],[P_Touch],[Remarks],[Reseaon],[Massage])values({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10});",
            db.DB_Safe_String(Id), db.DB_Safe_String(DoctorId), db.DB_Safe_String(Patient.UserId), db.DB_Safe_DateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), db.DB_Safe_String(Property_Ask), db.DB_Safe_String(Property_Look), db.DB_Safe_String(Property_Listen), db.DB_Safe_String(Property_Touch), db.DB_Safe_String(Remarks), db.DB_Safe_String(Reseaon), db.DB_Safe_String(Massage)));
        ta.Commit();

        return this;
    }

    public Diagnosis Update()
    {
        DB db = DB.getInstance();
        if (db.Affected(string.Format("Update [Diagnosis] set [CreateDate]={1},[P_Ask]={2},[P_Look]={3},[P_Listen]={4},[P_Touch]={5},[Remarks]={6},[Reseaon]={7},[Massage]={8} where [Id]={0}",
             db.DB_Safe_String(Id),db.DB_Safe_DateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), db.DB_Safe_String(Property_Ask), db.DB_Safe_String(Property_Look), db.DB_Safe_String(Property_Listen), db.DB_Safe_String(Property_Touch), db.DB_Safe_String(Remarks), db.DB_Safe_String(Reseaon), db.DB_Safe_String(Massage))) > 0)
        {
            db.Excute(string.Format("delete from [DiagnosisDrugs] where [Id]={0};", db.DB_Safe_String(Id)));
            StringBuilder sb = null;
            foreach (string i in Drugs)
            {
                if (sb == null)
                    sb = new StringBuilder();
                else
                    sb.Append(",");
                sb.Append(i);
            }
            db.Excute(string.Format("insert into [DiagnosisDrugs]([Id],[DrugsContent],[Status])values({0},{1},1);", db.DB_Safe_String(Id), db.DB_Safe_String(sb.ToString())));
        }
        return this;
    }

    public DataTable List(string DoctorId, string PatientId, string PatientName, string DateTimeBegin, string DateTimeEnd)
    {
        StringBuilder sb = null;
        DB db = DB.getInstance();
        //if (!string.IsNullOrEmpty(DoctorId))
        //{
        //    if (sb == null)
        //    {
        //        sb = new StringBuilder(" where");
        //    }
        //    else
        //    {
        //        sb.Append(" and");
        //    }
        //    sb.Append(string.Format(" a.[DoctorId]={0}", db.DB_Safe_String(DoctorId)));
        //}
        sb = new StringBuilder(string.Format(" where a.[DoctorId]={0}", db.DB_Safe_String(DoctorId)));
        if (!string.IsNullOrEmpty(PatientName))
        {
            if (sb == null)
            {
                sb = new StringBuilder(" where");
            }
            else
            {
                sb.Append(" and");
            }
            sb.Append(string.Format(" b.[UserName]={0}", db.DB_Safe_String(PatientName)));
        }
        if (!string.IsNullOrEmpty(DateTimeBegin))
        {
            if (sb == null)
            {
                sb = new StringBuilder(" where");
            }
            else
            {
                sb.Append(" and");
            }
            sb.Append(string.Format(" [a.CreateTime]>={0}", db.DB_Safe_DateTime(DateTimeBegin)));
        }
        if (!string.IsNullOrEmpty(DateTimeEnd))
        {
            if (sb == null)
            {
                sb = new StringBuilder(" where");
            }
            else
            {
                sb.Append(" and");
            }
            sb.Append(string.Format(" a.[CreateTime]<={0}", db.DB_Safe_DateTime(DateTimeEnd)));
        }
        return db.List(string.Format("select b.UserName,b.Telephone,b.UserSex,b.People,a.* from [Diagnosis] as a join UserExtense as b on a.PatientId=b.UserId{0};", sb == null ? string.Empty : sb.ToString()));
    }

    public void Delete()
    {
        DB db = DB.getInstance();

        db.Excute(string.Format("delete from [Diagnosis] where [Id]={0};", db.DB_Parse_String(Id)));
    }

    #endregion
}

public class DiagnosisDrugs
{
    public string Id { get; set; }
    public string DrugsContent { get; set; }
    public int Status { get; set; }

    public const string TAGSplitNameValue = "：";
    public const string TAGSplitPairsGrounp = "，";
    public const string TAGEND = "。";

    public DataTable List()
    {
        DB db = DB.getInstance();
        StringBuilder sb = null;//快乐：1，谢志丹：2。
        foreach (DataRow i in db.List(string.Format("select * from DiagnosisDrugs where Status={0}", db.DB_Safe_String(Status))).Rows)
        {
            DrugsContent = db.DB_Parse_String(i["DrugsContent"]);
            if (!string.IsNullOrEmpty(DrugsContent))
            {
                DrugsContent = DrugsContent.Substring(0, DrugsContent.Length - TAGEND.Length);
                StringDictionary sd = new StringDictionary();
                foreach (string j in DrugsContent.Split(new string[] { TAGSplitPairsGrounp }, StringSplitOptions.RemoveEmptyEntries))
                {
                    sd.Add(j.Substring(0, j.IndexOf(TAGSplitNameValue)), j.Substring(j.IndexOf(TAGSplitNameValue) + 1));
                }
                StringBuilder sbd = null;
                foreach (string s in sd.Keys)
                {
                    if (sbd == null)
                        sbd = new StringBuilder();
                    else
                        sbd.Append(",");
                    sbd.Append(db.DB_Safe_String(s));
                }
                DataTable dt;
                if (sbd != null)
                {
                    dt = db.List(string.Format("select * from Drugs where Status=1 and DrugsName in({0});", sbd.ToString()));
                }
                else
                {
                    dt = db.List(string.Format("select * from Drugs limit 0;"));
                }
                dt.Columns.Add(new DataColumn
                {
                    ColumnName = "Count",
                    DataType = typeof(string),
                    DefaultValue = DBNull.Value,
                });
                foreach (DataRow r in dt.Rows)
                {
                    string k = db.DB_Parse_String(r["DrugsName"]);
                    if (!sd.ContainsKey(k))
                    {
                        continue;
                    }
                    r["Count"] = sd[k];
                }
                return dt;
            }
        }

        return null;
    }

    public int ChangeStatus()
    {
        DB db = DB.getInstance();
        return db.Affected(string.Format("update DiagnosisDrugs set Status={1} where Id={0}", db.DB_Safe_String(Id), db.DB_Safe_Number(Status)));
    }
}

public class Drugs
{
    #region BaseProperty

    public string Id { get; set; }
    public string DrugsName { get; set; }
    public int OrderNumber { get; set; }
    public int Rate { get; set; }
    public int Status { get; set; }

    #endregion

    public DataTable List(string Status)
    {
        DB db = DB.getInstance();
        return db.List(string.Format("select * from Drugs{0} Order By OrderNumber desc", (string.IsNullOrEmpty(Status) ? string.Empty : " where Status=" + db.DB_Safe_Number(Status))));
    }

    public Drugs Insert()
    {
        DB db = DB.getInstance();
        db.Excute(string.Format("insert into [Drugs]([Id],[DrugsName],[OrderNumber],[Rate],[Status])values({0},{1},{2},{3},1)", db.DB_Safe_String(Id), db.DB_Safe_String(DrugsName), db.DB_Safe_String(DrugsName), db.DB_Safe_Number(OrderNumber), db.DB_Safe_Number(Rate)));
        return this;
    }

    public Drugs Update()
    {
        DB db = DB.getInstance();
        db.Excute(string.Format("update [Drugs] set [DrugsName]={1},[OrderNumber]={2},[Rate]={3},[Status]={4} where [Id]={0}", db.DB_Safe_String(Id), db.DB_Safe_String(DrugsName), db.DB_Safe_String(DrugsName), db.DB_Safe_Number(OrderNumber), db.DB_Safe_Number(Rate), db.DB_Safe_Number(Status)));
        return this;
    }

    public Drugs Delete()
    {
        DB db = DB.getInstance();
        db.Excute(string.Format("delete from [Drugs] where  [Id]={0}", db.DB_Safe_String(Id)));
        return this;
    }

    public DataRow Change(DataRow dr)
    {
        DB db = DB.getInstance();
        if (dr["Id"] == DBNull.Value)
        {
            Id = db.NewId;
            dr["Id"] = Id;
            db.Excute(string.Format("insert into [Drugs]([Id],[DrugsName],[OrderNumber],[Rate],[Status])values({0},{1},{2},{3},{4})", db.DB_Safe_String(Id), db.DB_Safe_String(dr["DrugsName"]), db.DB_Safe_Number(dr["OrderNumber"]), db.DB_Safe_Number(dr["Rate"]), db.DB_Safe_Number(dr["Status"])));
        }
        else
        {
            db.Excute(string.Format("update [Drugs] set [DrugsName]={1},[OrderNumber]={2},[Rate]={3},[Status]={4} where [Id]={0}", db.DB_Safe_String(dr["Id"]), db.DB_Safe_String(dr["DrugsName"]), db.DB_Safe_Number(dr["OrderNumber"]), db.DB_Safe_Number(dr["Rate"]), db.DB_Safe_Number(dr["Status"])));
        }
        return null;
    }
}